package com.ali.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 自定义全局过滤器
 */
@Slf4j
@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {
    public static final String START_TIME = "startTime";

    /**
     * 过滤规则
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        exchange.getAttributes().put(START_TIME, System.currentTimeMillis());
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            Long startTime = exchange.getAttribute(START_TIME);
            if (startTime != null) {
                Long endTime = System.currentTimeMillis();
                log.info("自定义全局过滤器：");
                log.info("请求开始时间：" + startTime);
                log.info("请求结束时间：" + endTime);
                log.info("请求时间：" + (endTime - startTime) + "ms");
                log.info("请求URL：" + exchange.getRequest().getURI());
            }
        }));
    }

    /**
     * 值越小，优先级越高
     */
    @Override
    public int getOrder() {
        return -1;
    }
}
